/**
 * farm_mager
 * @authors Your Name (you@example.org)
 * @date    2016-07-21 11:25:47
 * @version $Id$
 */

var farm_mager_seed_list = {
    sName: '冬瓜',
    sPrice: '10',
    sGtime: '30'
};

var farm_mager_seed_case = {
    cNum: 1,
    cContent: {
        p1: ['冬瓜', '西瓜', '南瓜', '北瓜'],
        p2: ['冬瓜', '西瓜', '南瓜', '北瓜'],
        p3: ['冬瓜', '西瓜', '南瓜', '北瓜']
    },
    isPublish: true
}

/**
 * ------------------------------------------------------------------------------------------农场管理者模块
 * @param  {[type]} $stateParams [description]
 * @return {[type]}              [description]
 */
var plant_list_test = [{
    Pnum: '1',
    Pphoto: './images/head_120.png',
    Pprice: '20¥',
    Parea: '10㎡'
}, {
    Pnum: '2',
    Pphoto: './images/head_120.png',
    Pprice: '20¥',
    Parea: '10㎡'
}, {
    Pnum: '3',
    Pphoto: './images/head_120.png',
    Pprice: '30¥',
    Parea: '20㎡'
}];

function DataList($http) {
    var list = [];
    this.set = function(data) {
        list.push(data)
    };
    this.get = function() {
        return list;
    };
    this.upload = function(url, method) {
        $http({
            url: url,
            method: method, //put更新,post添加
            data: list,
            headers: { 'Content-Type': 'application/json' }
        }).success(function(data, status, headers, config) {
            console.log('ok');
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    };
    this.clear = function() {
        list = [];
    };
}

function reader_img(id, img_url) {
    if (img_url) {
        var container = document.getElementById(id);
        var img = document.createElement('img');
        img.src = img_url;
        if (!container.hasChildNodes()) {
            container.appendChild(img);
        } else {
            container.replaceChild(img, container.firstElementChild);
        }
    }
};

function Plant($http) {
    this.plant_msg = undefined;
    this.$http = $http;
}
Plant.prototype = {
    constructor: Plant,
    add: function(callback, data) {
        this.$http({
            url: __API__._AddPlant_,
            method: "POST",
            data: data,
            // params: {},
            headers: { 'Content-Type': 'application/json' }
        }).success(function(data, status, headers, config) {
            log('add plant');
            callback(data);
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    },
    del: function(callback, data) {
        this.$http({
            url: __API__._AddPlant_,
            method: "DELETE",
            data: data,
            // params: {},
            headers: { 'Content-Type': 'application/json' }
        }).success(function(data, status, headers, config) {
            log('del plant');
            callback(data);
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    },
    up: function(callback, data) {
        this.$http({
            url: __API__._AddPlant_,
            method: "PUT",
            data: data,
            // params: {},
            headers: { 'Content-Type': 'application/json' }
        }).success(function(data, status, headers, config) {
            log('up plant');
            callback(data);
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    },
    get: function(callback) {},
    get_all: function(callback) {
        this.$http({
            url: __API__._AddPlant_,
            method: "GET",
            data: '',
            // params: {},
            headers: { 'Content-Type': 'application/json' }
        }).success(function(data, status, headers, config) {
            log('get all plant');
            callback(data);
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    }
}

function DataManager() {
    this.lists = [];
    this.data=undefined;
}
DataManager.prototype={
    constructor:DataManager,
    push:function(){},
    get_list:function(){},
    set_data:function(){},
    get_data:function(){}
}

function PubedManager($http) {
    this.plant_msg = undefined;
    this.$http = $http;
}
PubedManager.prototype = {
    constructor: PubedManager,
    get: function() {},
    get_all: function(callback) {
        this.$http({
            url: __API__._AddPlant_,
            method: "GET",
            data: '',
            // params: {},
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).success(function(data, status, headers, config) {
            log('get all plant');
            callback(data);
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    },
    up: function(data, callback) {
        this.$http({
            url: __API__._AddPlant_,
            method: "PUT",
            data: data,
            // params: {},
            headers: { 'Content-Type': 'application/json' }
        }).success(function(data, status, headers, config) {
            log('up plant');
            callback(data);
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    },
    del: function(data, callback) {
        this.$http({
            url: __API__._AddPlant_,
            method: "DELETE",
            data: data,
            // params: {},
            headers: { 'Content-Type': 'application/json' }
        }).success(function(data, status, headers, config) {
            log('del plant');
            callback(data);
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    },
    redo: function() {}
}

function EditingManager($http) {
    this.plant_msg = undefined;
    this.$http = $http;
}
EditingManager.prototype = {
    constructor: EditingManager,
    pub: function(data, callback) {
        this.$http({
            url: __API__._AddPlant_,
            method: "POST",
            data: data,
            // params: {},
            headers: { 'Content-Type': 'application/json' }
        }).success(function(data, status, headers, config) {
            log('add plant');
            callback(data);
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    }
}

function ctrl_farm_mager__pub_area($stateParams, $scope, $http) {
    //init
    (function() {
        $scope.upload_size = 0;
        $scope.upload_ed = 0;
        $scope.upload_pc = 0;
        $scope.upload_byte = 0;
    })();
    // $scope.dataset = plant_list_test;
    var pubed_list = new PubedManager($http);
    var editing_list = new EditingManager($http);

    (function() {
        pubed_list.get_all(function(data) {
            log(data.lands[0])
            $scope.pubed_list = data.lands;
        });
    })();

    $scope.editing_list = [];
    var con = 0;

    var mark_node = $$('data_waiting');
    var progerss_node = $$('fsUploadProgress');
    var loading = new Loading(mark_node);
    var progress = new Loading(progerss_node);

    //删除发布列表
    $scope.del_pubed_list = function(index, elem) {
        console.log(index)
        console.log(elem)
        $scope.pubed_list.splice(index, 1);

        pubed_list.del({ 'land_id': elem.land_id }, function(msg) {
            log(msg);
        })
    };

    //增添编辑列表
    $scope.add_edit_list = function() {
        $scope.editing_list.push(con++);
        console.log($scope.editing_list)
    };

    //删除编辑列表
    $scope.del_edit_list = function(index) {
        $scope.editing_list.splice(index, 1);
    };
    //提交发布列表
    $scope.sub_datalist = function() {
        var data_list = new DataList();
        var list = $$('pub_plant_editing_list').querySelectorAll('li');
        //console.log(list)

        for (var i = list.length - 1; i >= 0; i--) {
            var items = list[i].querySelectorAll('.data-edit');
            //自定义字段，很难再进行抽离
            data_list.set({
                'Pnum': items[0].value,
                'Pphoto': items[1].src,
                'Pprice': items[2].value,
                'Parea': items[3].value
            })
        }
        console.log(data_list.get())
    };

    //图片处理
    $scope.fileNameChanged = function(elem) {
        console.log(elem.dataset.class)

        var img_box = 'image' + elem.id;

        var id = elem.id;
        //display_img(id)

        var ifile = $$(id)
        console.log(ifile)
        uploader.setOption('img_box', img_box)
        uploader.addFile(ifile)
        console.log(uploader)
    };

    //下滑固定顶栏
    window.onscroll = function(ev) {
        fix_top('paper_top', 'paper-container-full');
    }

    //init上传环境
    var f_name = '';
    var file_type = [];
    var uploader = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: 'pickfiles',
        container: 'container',
        drop_element: 'container',
        flash_swf_url: 'bower_components/plupload/js/Moxie.swf',
        dragdrop: false,
        log_level: 3,
        //chunk_size: '4mb',
        multi_selection: false,
        uptoken_func: function() {
            console.log(file_type);
            var type = '.' + file_type.shift();
            //请求构造
            var q_url = 'http://106.75.137.2:8888/api/admin/pedia/up_token/?filename=';
            f_name = generateMixed(64) + type;
            q_url = q_url + f_name;
            var uptoken = '';
            var xhr = createXHR();

            xhrthen(xhr, function() {
                respon = JSON.parse(xhr.responseText);
                console.log(respon)
                uptoken = respon.up_token;
            });

            xhr.open('get', q_url, false);
            xhr.send();
            console.log(f_name)
            console.log(uptoken)
            return uptoken;
        },

        domain: "http://o8covea2w.bkt.clouddn.com/",
        get_new_uptoken: true,
        resize: {
            width: 512,
            height: 384,
            crop: true,
            quality: 100,
            preserve_headers: false
        },
        auto_start: true,
        init: {
            'QueueChanged': function(up) {
                console.log('change')
            },
            'FileFiltered': function(up, file) {
                console.log('file_init')
                var type = file.type.replace(/image\//g, '');
                console.log(type)
                file_type.push(type);
            },
            'FilesAdded': function(up, files) {
                console.log('add')
                console.log(files)
                loading.show();
            },
            'BeforeUpload': function(up, file) {
                console.log('before')
            },
            'UploadFile': function(up, file) {
                console.log('upload')
            },
            'UploadProgress': function(up, file) {},
            'UploadComplete': function() {
                file_type = [];
            },
            'FileUploaded': function(up, file, info) {
                console.log(info)
                var domain = up.getOption('domain');
                var res = eval('(' + info + ')');
                var sourceLink = domain + res.key; //获取上传文件的链接地址
                console.log(sourceLink);
                console.log(up.getOption('img_box'))
                reader_img(up.getOption('img_box'), sourceLink);
                loading.hide();
            },
            'Error': function(up, err, errTip) {

            },
            'Key': function(up, file) {
                var key = f_name;
                return key
            }
        }
    });


}

function display_img(id) {
    var up_file = document.getElementById(id);
    /**
     * 前置检测
     * @param  {[type]} this.files[0].type.indexOf('image') [description]
     * @return {[type]}                                     [description]
     */
    if (up_file.files[0].type.indexOf('image') === -1) {
        alert("您拖的不是图片！");
        return false;
    }
    var filesize = Math.floor((up_file.files[0].size) / 1024);
    if (filesize > 500) {
        alert("上传大小不能超过500K.");
        return false;
    }
    /**
     * 创建url
     * @type {[type]}
     */
    var icon_url = getImgUrl(up_file.files[0]);
    // var str = document.createElement('img');
    var img_id = id + 'image';
    var str = document.getElementById(img_id);
    console.log(img_id)
    str.src = icon_url;
    /**
     * 置入box
     * @type {[type]}
     */
    // var icon_box = document.getElementById('icon_box');
    // if (!icon_box.hasChildNodes()) {
    //     icon_box.appendChild(str);
    // } else {
    //     icon_box.replaceChild(str, icon_box.firstChild);
    // }
};

//发布种子子模块
/**
 * 种子列表
 * @param  {[type]} $stateParams [description]
 * @return {[type]}              [description]
 */
var seed_list_test = [{
    sName: '冬瓜',
    sPrice: '10', //¥
    sGtime: '30' //天
}, {
    sName: '系瓜',
    sPrice: '10', //¥
    sGtime: '30' //天
}, {
    sName: '南瓜',
    sPrice: '10', //¥
    sGtime: '30' //天
}]

function ctrl_farm_mager__pub_seed_case__seed_list($scope, $stateParams) {
    $scope.pubed_list = seed_list_test;
    $scope.editing_list = [];
    var con = 0;
    //删除发布列表
    $scope.del_pubed_list = function(index, elem) {
        console.log(index)
        console.log(elem)
        $scope.pubed_list.splice(index, 1);
    };

    //增添编辑列表
    $scope.add_edit_list = function() {
        $scope.editing_list.push(con++);
        console.log($scope.editing_list)
    };

    //删除编辑列表
    $scope.del_edit_list = function(index) {
        $scope.editing_list.splice(index, 1);
    };

    //下滑固定顶栏
    window.onscroll = function(ev) {
        fix_top('paper_top', 'paper-container-sright');
    }
}
/**
 * 发布种子方案
 * @param  {[type]} $stateParams [description]
 * @return {[type]}              [description]
 */
var seed_case_test = [{
    cNum: 1,
    cContent: {
        p1: ['undefine', '冬瓜', '西瓜', '南瓜', '北瓜'],
        p2: ['undefine', '冬瓜', '西瓜', '南瓜', '北瓜'],
        p3: ['undefine', '冬瓜', '西瓜', '南瓜', '北瓜']
    },
    isPublish: true
}, {
    cNum: 2,
    cContent: {
        p1: ['undefine', '冬瓜', '西瓜', '南瓜', '北瓜'],
        p2: ['undefine', '冬瓜', '西瓜', '南瓜', '北瓜'],
        p3: ['undefine', '冬瓜', '西瓜', '南瓜', '北瓜']
    },
    isPublish: false
}, {
    cNum: 3,
    cContent: {
        p1: ['undefine', '冬瓜', '西瓜', '南瓜', '北瓜'],
        p2: ['undefine', '冬瓜', '西瓜', '南瓜', '北瓜'],
        p3: ['undefine', '冬瓜', '西瓜', '南瓜', '北瓜']
    },
    isPublish: true
}]

function ctrl_farm_mager__pub_seed_case__seed_case($scope, $stateParams) {
    $scope.pubed_list = seed_case_test;
    $scope.editing_list = [];
    $scope.category = '';
    console.log(seed_case_test)
    $scope.edit_selector = seed_case_test[0].cContent.p1;
    var con = 0;

    //删除发布列表
    $scope.del_pubed_list = function(index, elem) {
        console.log(index)
        console.log(elem)
        $scope.pubed_list.splice(index, 1);
    };

    //增添编辑列表
    $scope.add_edit_list = function() {
        $scope.editing_list.push(con++);
        console.log($scope.editing_list)
    };

    //删除编辑列表
    $scope.del_edit_list = function(index) {
        $scope.editing_list.splice(index, 1);
    };

    //下滑固定顶栏
    window.onscroll = function(ev) {
        fix_top('paper_top', 'paper-container-sright');
    }
}


var sever_pck_test = [{
    Scon: 10,
    Sprice: 50,
    Sstatu: true
}, {
    Scon: 10,
    Sprice: 50,
    Sstatu: false
}, {
    Scon: 10,
    Sprice: 50,
    Sstatu: true
}]

// function msg_callback(main) {
//     main();
//     // history.back();
//     // var goback = function() {
//     //     history.back();
//     // };
//     // return { goback: goback }
// };
/**
 * 发布服务包
 * @param  {[type]} $stateParams [description]
 * @param  {[type]} $scope       [description]
 * @param  {[type]} $state       [description]
 * @param  {[type]} $rootScope   [description]
 * @return {[type]}              [description]
 */
function ctrl_farm_mager__pub_server_pck($stateParams, $scope, $state, $rootScope) {
    $scope.editing_list = [];
    console.log()
    var con = 0;
    $scope.dataset = sever_pck_test;

    /**
     * 改变发布列表的发布状态
     * @param  {[type]} index [description]
     * @return {[type]}       [description]
     */
    $scope.pub_toggle_statu = function(index) {
        /**
         * 使用rootscope建立回调函数
         * @type {[type]}
         */
        $rootScope.msg_index = index;
        /**
         * 分为main部分，以及callback部分
         * @return {[type]} [description]
         */
        $rootScope.msg_callback = function() {
            var index = $rootScope.msg_index;
            if ($scope.dataset[index].Sstatu)
                $scope.dataset[index].Sstatu = false;
            else $scope.dataset[index].Sstatu = true;

            var goback = function() {
                console.log('msg back')
                history.back();
            };
            return { goback: goback }

        };

        //console.log($rootScope.msg_callback)
        $state.go('farm_mager__pub_server_pck.msg_nal');
    };


    /**
     * 改变编辑列表的发布状态
     * @param  {[type]} index [description]
     * @return {[type]}       [description]
     */
    $scope.edit_toggle_statu = function(index) {};
    /**
     * 删除发布列表
     * @param  {[type]} index [description]
     * @return {[type]}       [description]
     */
    $scope.del_pubed_list = function(index) {
        $scope.dataset.splice(index, 1);
    };
    /**
     * 删除编辑列表
     * @param  {[type]} index [description]
     * @return {[type]}       [description]
     */
    $scope.del_edit_list = function(index) {
        $scope.editing_list.splice(index, 1);
    };
    /**
     * 增加编辑列表
     */
    $scope.add_edit_list = function() {
        $scope.editing_list.push(con++);
        console.log($scope.editing_list)
    };

}
